# -*- coding: utf-8 -*-
"""
固定资产管理系统 - 仪表板小部件
"""

from django.db.models import Count, Q, Sum, F
from django.utils import timezone
from datetime import datetime, timedelta
import json


class DashboardWidgets:
    """仪表板小部件集合"""
    
    @staticmethod
    def get_asset_overview():
        """获取资产概览数据"""
        try:
            from .models import Asset, AssetCategory
            
            # 总体统计
            total_count = Asset.objects.count()
            active_count = Asset.objects.filter(status='active').count()
            idle_count = Asset.objects.filter(status='idle').count()
            maintenance_count = Asset.objects.filter(status='maintenance').count()
            
            # 按类别统计
            category_stats = list(AssetCategory.objects.annotate(
                asset_count=Count('asset')
            ).values('name', 'asset_count', 'code'))
            
            # 按状态统计
            status_stats = {
                'active': active_count,
                'idle': idle_count,
                'maintenance': maintenance_count,
                'total': total_count
            }
            
            return {
                'status': 'success',
                'data': {
                    'overview': status_stats,
                    'categories': category_stats,
                    'usage_rate': round((active_count / total_count * 100) if total_count > 0 else 0, 1)
                }
            }
        except Exception as e:
            return {'status': 'error', 'message': str(e)}
    
    @staticmethod
    def get_borrow_statistics():
        """获取借用统计数据"""
        try:
            from .models import AssetBorrow
            
            # 当前借用
            current_borrows = AssetBorrow.objects.filter(status='borrowed').count()
            
            # 逾期借用
            overdue_borrows = AssetBorrow.objects.filter(
                status='borrowed',
                expected_return_date__lt=timezone.now().date()
            ).count()
            
            # 今日到期
            today = timezone.now().date()
            due_today = AssetBorrow.objects.filter(
                status='borrowed',
                expected_return_date=today
            ).count()
            
            # 本月借用趋势
            month_start = today.replace(day=1)
            monthly_borrows = AssetBorrow.objects.filter(
                created_at__gte=month_start
            ).count()
            
            return {
                'status': 'success',
                'data': {
                    'current': current_borrows,
                    'overdue': overdue_borrows,
                    'due_today': due_today,
                    'monthly_new': monthly_borrows
                }
            }
        except Exception as e:
            return {'status': 'error', 'message': str(e)}
    
    @staticmethod
    def get_inventory_alerts():
        """获取库存预警信息"""
        try:
            from .models import Consumable, Warehouse
            
            # 低库存预警
            low_stock_items = Consumable.objects.filter(
                quantity__lte=F('min_quantity')
            ).count() if hasattr(Consumable, 'min_quantity') else 0
            
            # 零库存
            zero_stock = Consumable.objects.filter(quantity=0).count()
            
            # 仓库统计
            warehouse_count = Warehouse.objects.count()
            
            # 总耗材种类
            total_consumables = Consumable.objects.count()
            
            return {
                'status': 'success',
                'data': {
                    'low_stock': low_stock_items,
                    'zero_stock': zero_stock,
                    'warehouses': warehouse_count,
                    'total_items': total_consumables
                }
            }
        except Exception as e:
            return {'status': 'error', 'message': str(e)}
    
    @staticmethod
    def get_system_health():
        """获取系统健康状态"""
        try:
            import psutil
            from django.db import connection
            
            # CPU和内存使用率
            cpu_percent = psutil.cpu_percent(interval=1)
            memory = psutil.virtual_memory()
            
            # 数据库连接测试
            try:
                with connection.cursor() as cursor:
                    cursor.execute("SELECT 1")
                db_status = 'healthy'
            except Exception:
                db_status = 'error'
            
            # 磁盘使用率
            try:
                disk = psutil.disk_usage('/')
                disk_percent = disk.percent
            except Exception:
                disk_percent = 0
            
            return {
                'status': 'success',
                'data': {
                    'cpu_percent': cpu_percent,
                    'memory_percent': memory.percent,
                    'disk_percent': disk_percent,
                    'database_status': db_status,
                    'timestamp': timezone.now().isoformat()
                }
            }
        except Exception as e:
            return {'status': 'error', 'message': str(e)}
    
    @staticmethod
    def get_recent_activities():
        """获取最近活动"""
        try:
            from .models import Asset, AssetBorrow, AssetLog
            
            # 最近添加的资产
            recent_assets = Asset.objects.order_by('-created_at')[:5].values(
                'name', 'asset_number', 'created_at', 'category__name'
            )
            
            # 最近借用记录
            recent_borrows = AssetBorrow.objects.order_by('-created_at')[:5].values(
                'asset__name', 'borrower__username', 'status', 'created_at'
            )
            
            # 最近系统日志
            recent_logs = AssetLog.objects.order_by('-created_at')[:5].values(
                'asset__name', 'action', 'operator__username', 'created_at'
            )
            
            return {
                'status': 'success',
                'data': {
                    'assets': list(recent_assets),
                    'borrows': list(recent_borrows),
                    'logs': list(recent_logs)
                }
            }
        except Exception as e:
            return {'status': 'error', 'message': str(e)}
    
    @staticmethod
    def get_monthly_trends():
        """获取月度趋势数据"""
        try:
            from .models import Asset, AssetBorrow
            
            # 获取最近6个月的数据
            trends = []
            for i in range(6):
                month = timezone.now().date().replace(day=1) - timedelta(days=30*i)
                
                # 该月新增资产
                new_assets = Asset.objects.filter(
                    created_at__year=month.year,
                    created_at__month=month.month
                ).count()
                
                # 该月新增借用
                new_borrows = AssetBorrow.objects.filter(
                    created_at__year=month.year,
                    created_at__month=month.month
                ).count()
                
                trends.append({
                    'month': month.strftime('%Y-%m'),
                    'assets': new_assets,
                    'borrows': new_borrows
                })
            
            return {
                'status': 'success',
                'data': {
                    'trends': trends[::-1]  # 反转顺序，从早到晚
                }
            }
        except Exception as e:
            return {'status': 'error', 'message': str(e)}
    
    @staticmethod
    def get_department_statistics():
        """获取部门统计数据"""
        try:
            from .models import Department, Asset
            
            # 按部门统计资产
            dept_stats = Department.objects.annotate(
                asset_count=Count('asset')
            ).values('name', 'asset_count', 'organization__name')
            
            # 前5名部门
            top_departments = sorted(dept_stats, key=lambda x: x['asset_count'], reverse=True)[:5]
            
            return {
                'status': 'success',
                'data': {
                    'departments': list(dept_stats),
                    'top_5': top_departments
                }
            }
        except Exception as e:
            return {'status': 'error', 'message': str(e)}
    
    @classmethod
    def get_all_widgets_data(cls):
        """获取所有小部件数据"""
        return {
            'asset_overview': cls.get_asset_overview(),
            'borrow_statistics': cls.get_borrow_statistics(),
            'inventory_alerts': cls.get_inventory_alerts(),
            'system_health': cls.get_system_health(),
            'recent_activities': cls.get_recent_activities(),
            'monthly_trends': cls.get_monthly_trends(),
            'department_statistics': cls.get_department_statistics(),
        }